package client.taxiapp.com.taxiapp.service;

import android.app.Service;
import android.content.Intent;
import android.os.IBinder;
import android.support.annotation.Nullable;
import android.util.Log;

import com.alibaba.fastjson.JSON;

import java.util.concurrent.Executors;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.TimeUnit;

import client.taxiapp.com.taxiapp.domain.BaseResponse;
import client.taxiapp.com.taxiapp.retrofit.UserService;
import client.taxiapp.com.taxiapp.util.Constant;
import client.taxiapp.com.taxiapp.util.RetrofitUtil;
import client.taxiapp.com.taxiapp.util.Util;
import retrofit.Call;
import retrofit.Callback;
import retrofit.Response;
import retrofit.Retrofit;

/**
 * Created by Amence on 2018/4/29.
 */

public class PassengerServer extends Service {

    ScheduledExecutorService scheduleForPassengerPull = null;
    
    private String   allPassengerJson = null;


    @Nullable
    @Override
    public IBinder onBind(Intent intent) {
        return null;
    }

    @Override
    public void onCreate() {
        super.onCreate();


        scheduleForPassengerPull = Executors.newSingleThreadScheduledExecutor();
        scheduleForPassengerPull.scheduleWithFixedDelay(new Runnable() {
            public void run() {
                try {
                    Retrofit retrofit = RetrofitUtil.retrofitRequest();

                    UserService userService = retrofit.create(UserService.class);


                    Call<BaseResponse> call = userService.getAllPassenger();

                    call.enqueue(new Callback<BaseResponse>() {
                        @Override
                        public void onResponse(Response<BaseResponse> response, Retrofit retrofit) {

                            BaseResponse baseResponse = response.body();

                            if (baseResponse.getMeta().isResult()) {
                                allPassengerJson = JSON.toJSONString(baseResponse.getData());
                                Log.v("Amence", allPassengerJson);
                                Util.saveString(PassengerServer.this,Constant.SP_DRIVER_KEY,allPassengerJson);


                            } else {
                                String message = baseResponse.getMeta().getMsg();
                                Log.v("Amence", message);

                            }
                        }

                        @Override
                        public void onFailure(Throwable t) {
                            String message = t.getMessage();
                        }

                    });

                } catch (Throwable e) {
                    Log.v("Amence", "scheduleForPassengerPull error"+e.getMessage());
                }

            }
        }, Constant.DEFAULT_SCHEDULE_INITIAL_DELAY, Constant.DEFAULT_SCHEDULE_DELAY, TimeUnit.SECONDS);

        Log.v("Amence","PassengerServer-->onCreate()");

    }
}
